// Package meso 实现介观均衡引擎
// 基于四维一体法则的第二维度：介观均衡
package meso

import (
	"fmt"
	"math"
	"math/cmplx"
)

// QuantumState 量子态接口（与micro包共享）
type QuantumState interface {
	GetAmplitudes() []complex128
	GetCoherence() float64
	SetCoherence(float64)
}

// DynamicBalanceEngine 动态平衡引擎
type DynamicBalanceEngine struct {
	ChaosThreshold  float64 // 混沌阈值 (0-1)
	OrderThreshold  float64 // 有序阈值 (0-1)
	EntropyHistory  []float64
	BalanceHistory  []BalanceSnapshot
	MaxHistorySize  int
}

// BalanceSnapshot 平衡快照
type BalanceSnapshot struct {
	Timestamp    int64
	Entropy      float64
	BalanceState string // "chaos", "order", "equilibrium"
	Action       string // 采取的行动
}

// NewDynamicBalanceEngine 创建新的动态平衡引擎
func NewDynamicBalanceEngine(chaosThreshold, orderThreshold float64) *DynamicBalanceEngine {
	return &DynamicBalanceEngine{
		ChaosThreshold: chaosThreshold,
		OrderThreshold: orderThreshold,
		EntropyHistory: make([]float64, 0),
		BalanceHistory: make([]BalanceSnapshot, 0),
		MaxHistorySize: 1000,
	}
}

// MaintainEquilibrium 维持动态平衡
func (e *DynamicBalanceEngine) MaintainEquilibrium(states interface{}) error {
	// 计算系统熵
	entropy := e.CalculateSystemEntropy(states)
	
	// 记录熵历史
	e.recordEntropy(entropy)
	
	// 判断系统状态并采取行动
	var action string
	var err error
	
	if entropy > e.ChaosThreshold {
		// 系统过于混沌，需要引入有序
		action = "apply_quantum_correction"
		err = e.ApplyQuantumCorrection(states)
	} else if entropy < e.OrderThreshold {
		// 系统过于有序，需要引入混沌
		action = "introduce_chaos"
		err = e.IntroduceChaos(states, 0.1)
	} else {
		// 系统处于理想平衡态
		action = "maintain"
		err = nil
	}
	
	// 记录平衡状态
	e.recordBalance(entropy, e.getBalanceState(entropy), action)
	
	return err
}

// CalculateSystemEntropy 计算系统熵
func (e *DynamicBalanceEngine) CalculateSystemEntropy(states interface{}) float64 {
	// 根据不同类型计算熵
	switch v := states.(type) {
	case []float64:
		return e.calculateDiscreteEntropy(v)
	case []complex128:
		return e.calculateQuantumEntropy(v)
	default:
		return 0.5 // 默认中等熵
	}
}

// calculateDiscreteEntropy 计算离散熵（Shannon熵）
func (e *DynamicBalanceEngine) calculateDiscreteEntropy(probabilities []float64) float64 {
	var entropy float64
	
	// 归一化概率
	sum := 0.0
	for _, p := range probabilities {
		sum += p
	}
	
	if sum == 0 {
		return 0
	}
	
	// 计算香农熵
	for _, p := range probabilities {
		if p > 0 {
			normalizedP := p / sum
			entropy -= normalizedP * math.Log2(normalizedP)
		}
	}
	
	// 归一化到 [0, 1]
	maxEntropy := math.Log2(float64(len(probabilities)))
	if maxEntropy > 0 {
		entropy /= maxEntropy
	}
	
	return entropy
}

// calculateQuantumEntropy 计算量子熵（Von Neumann熵）
func (e *DynamicBalanceEngine) calculateQuantumEntropy(amplitudes []complex128) float64 {
	// 计算密度矩阵的特征值
	probabilities := make([]float64, len(amplitudes))
	for i, amp := range amplitudes {
		probabilities[i] = real(amp)*real(amp) + imag(amp)*imag(amp)
	}
	
	return e.calculateDiscreteEntropy(probabilities)
}

// ApplyQuantumCorrection 应用量子纠错
func (e *DynamicBalanceEngine) ApplyQuantumCorrection(states interface{}) error {
	// 实现量子纠错算法
	// 这里使用简化的bit-flip纠错
	
	switch v := states.(type) {
	case []complex128:
		return e.correctQuantumStates(v)
	default:
		return fmt.Errorf("不支持的状态类型")
	}
}

// correctQuantumStates 纠正量子态
func (e *DynamicBalanceEngine) correctQuantumStates(amplitudes []complex128) error {
	// 找出偏离最大的态并进行修正
	avgAmplitude := complex(1.0/math.Sqrt(float64(len(amplitudes))), 0)
	
	for i := range amplitudes {
		// 如果振幅偏离太大，拉回到平均值附近
		deviation := amplitudes[i] - avgAmplitude
		if cmplx.Abs(deviation) > 0.3 {
			amplitudes[i] -= deviation * 0.5 // 修正50%的偏离
		}
	}
	
	// 重新归一化
	e.normalizeAmplitudes(amplitudes)
	
	return nil
}

// IntroduceChaos 引入创造性混沌
func (e *DynamicBalanceEngine) IntroduceChaos(states interface{}, level float64) error {
	if level < 0 || level > 1 {
		return fmt.Errorf("混沌水平必须在[0,1]之间")
	}
	
	switch v := states.(type) {
	case []complex128:
		return e.addQuantumNoise(v, level)
	default:
		return fmt.Errorf("不支持的状态类型")
	}
}

// addQuantumNoise 添加量子噪声
func (e *DynamicBalanceEngine) addQuantumNoise(amplitudes []complex128, noiseLevel float64) error {
	for i := range amplitudes {
		// 添加随机相位噪声
		noise := complex(
			(math.Sin(float64(i)*3.14159)*noiseLevel - noiseLevel/2),
			(math.Cos(float64(i)*2.71828)*noiseLevel - noiseLevel/2),
		)
		amplitudes[i] += noise
	}
	
	// 重新归一化
	e.normalizeAmplitudes(amplitudes)
	
	return nil
}

// GetEntropyTrend 获取熵趋势
func (e *DynamicBalanceEngine) GetEntropyTrend() string {
	if len(e.EntropyHistory) < 2 {
		return "stable"
	}
	
	recent := e.EntropyHistory[len(e.EntropyHistory)-1]
	previous := e.EntropyHistory[len(e.EntropyHistory)-2]
	
	diff := recent - previous
	if diff > 0.05 {
		return "increasing"
	} else if diff < -0.05 {
		return "decreasing"
	}
	return "stable"
}

// GetBalanceReport 获取平衡报告
func (e *DynamicBalanceEngine) GetBalanceReport() map[string]interface{} {
	currentEntropy := 0.0
	if len(e.EntropyHistory) > 0 {
		currentEntropy = e.EntropyHistory[len(e.EntropyHistory)-1]
	}
	
	return map[string]interface{}{
		"current_entropy":  currentEntropy,
		"chaos_threshold":  e.ChaosThreshold,
		"order_threshold":  e.OrderThreshold,
		"balance_state":    e.getBalanceState(currentEntropy),
		"entropy_trend":    e.GetEntropyTrend(),
		"history_size":     len(e.EntropyHistory),
		"recent_snapshots": e.getRecentSnapshots(5),
	}
}

// 辅助方法

func (e *DynamicBalanceEngine) recordEntropy(entropy float64) {
	e.EntropyHistory = append(e.EntropyHistory, entropy)
	if len(e.EntropyHistory) > e.MaxHistorySize {
		e.EntropyHistory = e.EntropyHistory[1:]
	}
}

func (e *DynamicBalanceEngine) recordBalance(entropy float64, state, action string) {
	snapshot := BalanceSnapshot{
		Timestamp:    0, // 可以用time.Now().Unix()
		Entropy:      entropy,
		BalanceState: state,
		Action:       action,
	}
	
	e.BalanceHistory = append(e.BalanceHistory, snapshot)
	if len(e.BalanceHistory) > e.MaxHistorySize {
		e.BalanceHistory = e.BalanceHistory[1:]
	}
}

func (e *DynamicBalanceEngine) getBalanceState(entropy float64) string {
	if entropy > e.ChaosThreshold {
		return "chaos"
	} else if entropy < e.OrderThreshold {
		return "order"
	}
	return "equilibrium"
}

func (e *DynamicBalanceEngine) getRecentSnapshots(n int) []BalanceSnapshot {
	if len(e.BalanceHistory) <= n {
		return e.BalanceHistory
	}
	return e.BalanceHistory[len(e.BalanceHistory)-n:]
}

func (e *DynamicBalanceEngine) normalizeAmplitudes(amplitudes []complex128) {
	var sum float64
	for _, amp := range amplitudes {
		sum += real(amp)*real(amp) + imag(amp)*imag(amp)
	}
	
	norm := math.Sqrt(sum)
	if norm > 0 {
		for i := range amplitudes {
			amplitudes[i] /= complex(norm, 0)
		}
	}
}


